package com.linked.usermanage.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.universal.common.Result;
import com.linked.commonentity.usermanage.info.LinkedUserInfo;
import com.linked.usermanage.login.bean.po.LoginPO;
import com.linked.usermanage.login.service.ILoginService;
import com.linked.usermanage.user.bean.dto.UserAllInfoDTO;
import com.linked.usermanage.user.bean.param.UserAllInfoParam;
import com.linked.usermanage.user.bean.param.UserAndLoginInfoParam;
import com.linked.usermanage.user.bean.param.UserContainsRolesParam;
import com.linked.usermanage.user.bean.param.UserPageParam;
import com.linked.usermanage.user.bean.po.UserInfoPO;
import com.linked.usermanage.user.service.IUserHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author :dbq
 * @date : 2022/10/21 14:02
 */
@RestController
@RequestMapping("/userhandle")
public class UserHandleController {


    private final static Logger logger = LoggerFactory.getLogger(UserHandleController.class);

    private final ObjectMapper mapper;

    private final IUserHandleService userHandleService;

    private final ILoginService loginService;

    @Autowired
    public UserHandleController(ObjectMapper mapper, IUserHandleService userHandleService, ILoginService loginService) {
        this.mapper = mapper;
        this.userHandleService = userHandleService;
        this.loginService = loginService;
    }

    @PostMapping("addAUser")
    public Result addAUser(@RequestBody UserInfoPO param) throws JsonProcessingException {
        if (logger.isInfoEnabled()) {
            logger.info("新增用户接口,入参：{}", mapper.writeValueAsString(param));
        }

        boolean ret = false;
        try {
            ret = userHandleService.addAUser(param);
        } catch (Exception e) {
            logger.error("新增用户接口异常！", e);
        }
        return ret ? Result.ok(true, "新增用户成功！") : Result.ok(false, "新增用户失败！");
    }

    /**
     * 新增用户及登录信息接口
     */
    @PostMapping("addUserWithLoginInfo")
    @Transactional(readOnly = true, rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
    public Result addUserWithLoginInfo(@RequestBody UserAndLoginInfoParam param) throws Exception {

        if (logger.isInfoEnabled()) {
            logger.info("新增用户及登录信息接口,入参：{}", mapper.writeValueAsString(param));
        }
        /**
         * 保存登录信息
         * */
        LoginPO loginTemp = new LoginPO();
        loginTemp.setUsername(param.getLoginName());
        loginTemp.setPassword(param.getPassword());
        boolean loginRet = loginService.saveLoginInfo(loginTemp);
        if (!loginRet) {
            return Result.ok(false, "新增用户失败！");
        }
        /**
         * 保存用户信息
         * */
        UserInfoPO userTemp = new UserInfoPO(param);
        userTemp.setLoginId(loginTemp.getLoginId());
        boolean ret = userHandleService.addAUser(userTemp);

        return ret ? Result.ok(true, "新增用户成功！") : Result.ok(false, "新增用户失败！");
    }

    @PostMapping("queryUserPage")
    Result queryUserPage(@RequestBody UserPageParam param) throws JsonProcessingException {
        if (logger.isInfoEnabled()) {
            logger.info("查询用户页面接口,入参：{}", mapper.writeValueAsString(param));
        }

        IPage<UserInfoPO> res = null;
        try {
            res = userHandleService.queryUserPage(param);
        } catch (Exception e) {
            logger.error("查询用户页面接口异常！");
            return Result.error();
        }
        return Result.success(res);
    }

    @PostMapping("addRolesToUser")
    Result addRolesToUser(@RequestBody UserContainsRolesParam param) throws JsonProcessingException {
        if (logger.isInfoEnabled()) {
            logger.info("用户加权限接口,入参：{}", mapper.writeValueAsString(param));
        }
        boolean ret = false;
        try {
            ret = userHandleService.addRolesToUser(param);
        } catch (Exception e) {
            logger.error("用户加权限接口异常！", e);
        }

        return ret ? Result.success() : Result.ok(false, "");
    }

    @PostMapping("getUserAllInfo")
    Result getUserAllInfo(@RequestBody UserAllInfoParam param) throws Exception {
        if (logger.isInfoEnabled()) {
            logger.info("获取用户所有信息接口,入参：{}", mapper.writeValueAsString(param));
        }
        if (StringUtils.isEmpty(param.getUserId()) && StringUtils.isEmpty(param.getLoginId())) {
            return Result.error("用户id或登录id不能为空！");
        }
        if (StringUtils.isEmpty(param.getUserId()) && !StringUtils.isEmpty(param.getLoginId())) {
            String userId = userHandleService.queryUserIdByLoginId(param.getLoginId());
            if (!StringUtils.isEmpty(userId)) {
                param.setUserId(userId);
            } else {
                return Result.ok(false, "用户登录信息错误！");
            }
        }
        UserAllInfoDTO res = null;
        try {
            res = userHandleService.getUserAllInfo(param);
        } catch (Exception e) {
            logger.error("获取用户所有信息接口异常！", e);
        }
        return Result.success(res);
    }

//    @PostMapping("queryAllUserList")
//    public Result queryAllUserList() throws JsonProcessingException {
//
//        List<UserInfoPO> res = null;
//        List<LinkedUserInfo> finalRes = new ArrayList<>();
//        try {
//            res = userHandleService.queryAllUserList();
//            finalRes = res.stream().map(x -> {
//                LinkedUserInfo temp = new LinkedUserInfo();
//                temp.setUserName(x.getUserName());
//                return temp;
//            }).collect(Collectors.toList());
//        } catch (Exception e) {
//            logger.error("查询所有用户列表接口异常！");
//            return Result.error();
//        }
//        return Result.success(mapper.writeValueAsString(finalRes));
//    }



}
